<?php

namespace PolarisbackEndFrameRe\api\request\http;

/**
 * 发送请求
 * @author TINUOKAS1/Astoflow
 */
class SendRequest {

    /**
     * 构造函数
     * @param string $url
     * @param string $mode
     * @param array $data
     * @return void
     */
    public function __construct(string $url, string $mode, array $data = [])
    {
        switch ($mode) {
            case "get":
                $this->sendGetRequest($url);
                break;
            case "post":
                $this->sendPostRequest($url, $data);
                break;
            case "put":
                $this->sendPutRequest($url, $data);
                break;
            case "delete":
                $this->sendDeleteRequest($url);
                break;
            default:
                throw new \InvalidArgumentException("Unsupported request mode: $mode");
        }
    }

    /**
     * 发送GET请求
     * @param string $url
     * @return void
     */
    public function sendGetRequest(string $url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // 不接收响应

        curl_exec($ch);

        if (curl_errno($ch)) {
            die('Error: ' . curl_error($ch));
        }

        curl_close($ch);
    }

    /**
     * 发送POST请求
     * @param string $url
     * @param array $data
     * @return void
     */
    public function sendPostRequest(string $url, array $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // 不接收响应

        curl_exec($ch);

        if (curl_errno($ch)) {
            die('Error: ' . curl_error($ch));
        }

        curl_close($ch);
    }

    /**
     * 发送PUT请求
     * @param string $url
     * @param array $data
     * @return void
     */
    public function sendPutRequest(string $url, array $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // 不接收响应

        curl_exec($ch);

        if (curl_errno($ch)) {
            die('Error: ' . curl_error($ch));
        }

        curl_close($ch);
    }

    /**
     * 发送DELETE请求
     * @param string $url
     * @return void
     */
    public function sendDeleteRequest(string $url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // 不接收响应

        curl_exec($ch);

        if (curl_errno($ch)) {
            die('Error: ' . curl_error($ch));
        }

        curl_close($ch);
    }
}